<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserLists">
            <el-button slot="append" icon="el-icon-search" @click="getUserLists"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"> </el-switch>
          </template>
          <!-- <el-switch v-model=""> </el-switch> -->
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 主体 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 主体 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editForm.id)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRolesDialogVisible" width="50%" @close="setRoleClose">
      <div>
        <p>当前用户：{{ userinfo.username }}</p>
        <p>当前角色：{{ userinfo.role_name }}</p>
        <p>
          分配角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="seveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, editUserStatus, addUser, findUser, editUser, delUser, getRolesList, saveRole } from '@/api'
export default {
  name: 'UserIndex',
  data() {
    // 定义校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!regEmail.test(value)) {
        callback(new Error('格式错误'))
      }
      return callback()
    }
    const checkmobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!regMobile.test(value)) {
        callback(new Error('格式错误'))
      }
      return callback()
    }

    return {
      // 获取用户列表数据
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 添加用户
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在3-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名长度在6-15之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 修改用户
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 分配角色
      setRolesDialogVisible: false,
      // 需要被分配角色的用户信息
      userinfo: {},
      rolesList: [],
      // 被选中的角色id
      selectRoleId: ''
    }
  },
  created() {
    this.getUserLists()
  },
  methods: {
    // 获取数据
    async getUserLists() {
      const { data: res } = await getUserList(this.queryInfo)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败！')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize每页显示数据
    handleSizeChange(val) {
      console.log(val)
      this.queryInfo.pagesize = val
      this.getUserLists()
    },
    // 页码值
    handleCurrentChange(val) {
      console.log(val)
      this.queryInfo.pagenum = val
      this.getUserLists()
    },
    // 修改用户状态
    async userStateChange(val) {
      console.log(val)
      const { data: res } = await editUserStatus(val.id, val.mg_state)
      console.log(res)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 关闭弹出层
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户确定事件
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return ''
        const { data: res } = await addUser(this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 关闭弹层
        this.addDialogVisible = false
        // 重新获取用户列表
        this.getUserLists()
      })
    },
    // 修改用户弹出事件
    async showEditDialog(id) {
      this.editDialogVisible = true
      console.log(id)
      const { data: res } = await findUser(id)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      console.log(res)
      this.editForm = res.data
    },
    // 编辑用户确定事件
    async editUser(id) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return ''
        const { data: res } = await editUser(id, this.editForm)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        this.editDialogVisible = false
        this.getUserLists()
      })
    },
    // 删除用户事件
    async removeUser(id) {
      console.log(id)
      const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err) // catch捕获删除返回cancel
      // 确认删除会输出confirm字符串，取消会报错
      console.log(confirmRes)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消')
      }
      const { data: res } = await delUser(id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserLists()
    },
    // 分配角色点击事件
    async setRole(val) {
      this.setRolesDialogVisible = true
      this.userinfo = val
      const { data: res } = await getRolesList()
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色数据失败')
      this.rolesList = res.data
    },
    // 分配角色确定事件
    async seveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.warning('请选择要分配的角色')
      }
      const { data: res } = await saveRole(this.userinfo.id, this.selectRoleId)
      if (res.meta.status !== 200) return this.$message.error('设置用户角色失败')
      this.$message.success('设置成功')
      this.getUserLists()
      this.setRolesDialogVisible = false
    },
    // 分配角色对话框关闭事件
    setRoleClose() {
      this.selectRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped></style>
